import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 使用本地文件路径
file_path = r"D:\codepython\qie.csv"
# 读取 CSV 文件
df = pd.read_csv(file_path)

# 打印数据框的前几行，以验证数据是否正确读取
print(df.head(5))

# 显示缺失值的行
print(df[df.isnull().any(axis=1)])

# 删除包含缺失值的行
df = df.dropna()

# 可视化数据
plt.figure(figsize=(10, 6))
sns.countplot(x='Species', data=df)
plt.title('Distribution of Penguin Species')
plt.show()

plt.figure(figsize=(10, 6))
sns.boxplot(x='Species', y='FlipperLength', data=df)
plt.title('Flipper Length by Species')
plt.show()

plt.figure(figsize=(10, 6))
sns.boxplot(x='Species', y='CulmenLength', data=df)
plt.title('Culmen Length by Species')
plt.show()

plt.figure(figsize=(10, 6))
sns.boxplot(x='Species', y='CulmenDepth', data=df)
plt.title('Culmen Depth by Species')
plt.show()

# 准备数据
features = ['CulmenLength', 'CulmenDepth', 'FlipperLength']
labels = 'Species'
X, y = df[features].values, df[labels].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)

# 训练模型
model = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=1000)
model.fit(X_train, y_train)

# 评估模型
y_hat = model.predict(X_test)
acc = accuracy_score(y_test, y_hat)
print('Accuracy:', acc)